package org.chench.extra.logsift.io;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;

/**
 * 文件随机读取工具，按行读取时，支持指定编码
 * @author chenchanghui
 * @date 2025/8/26
 */
public class CodifiableRandomAccessFile extends RandomAccessFile {
    public CodifiableRandomAccessFile(String name, String mode) throws FileNotFoundException {
        super(name, mode);
    }

    public CodifiableRandomAccessFile(File file, String mode) throws FileNotFoundException {
        super(file, mode);
    }

    /**
     * 按行读取方法，支持指定编码
     * @param encoding
     * @return
     * @throws IOException
     */
    public String readLineWithEncoding(String encoding) throws IOException {
        ByteArrayOutputStream byteArr = new ByteArrayOutputStream();
        int c = -1;
        boolean eol = false;
        while (!eol) {
            switch (c = read()) {
                // 遇到换行符则结束本行读取
                case -1:
                case '\n':
                    eol = true;
                    break;
                // 处理回车符
                case '\r':
                    eol = true;
                    // 查看下一个字符是否是换行符
                    long cur = getFilePointer();
                    if ((read()) != '\n') {
                        // 如果不是换行符，回退指针
                        seek(cur);
                    }
                    break;
                default:
                    byteArr.write(c);
                    break;
            }
        }

        if ((c == -1) && (byteArr.size() == 0)) {
            // 没有读取到内容，返回null表示文件结束
            return null;
        }

        return byteArr.toString(encoding);
    }

}
